/**
 * 登陆界面
 * by wyy
 */
class loginScene extends GameObject implements eui.UIComponent {
    public loginBtn: eui.Button;
    public idInput: eui.TextInput;
    public nameInput: eui.TextInput;
    public loginGrp: eui.Group;
    public logo: eui.Image;
    public displayGrp: eui.Group;
    public ruleBtn: eui.Button;

    type = "login";

    playerInfo: { id: number, deskid: number, result: string, roll_time: number } = {
        id: 0,
        deskid: 0,
        result: "",
        roll_time: 0
    };
    heightPercent = 1;
    widthPercent = 1;

    private static instance: loginScene;

    constructor() {
        super();
        this.skinName = "resource/eui_skins/game_skins/loginSceneSkin.exml";
    }

    static getInstance(): loginScene {
        (!this.instance) && (this.instance = new loginScene());
        return this.instance;
    }

    firstCreate() {
        //如果有本地存储 就填入输入栏
        this.idInput.text = egret.localStorage.getItem("loginId");
        this.nameInput.text = egret.localStorage.getItem("loginName");

        this.loginBtn.addEventListener(egret.TouchEvent.TOUCH_TAP, this.login, this);
        this.ruleBtn.addEventListener(egret.TouchEvent.TOUCH_TAP,
            () => { SceneManager.getInstance().showWindow(new helpScene()) }, this);
        //初始化骰子动画工厂
        globalObject.getInstance().diceFactory =
            new egret.MovieClipDataFactory(RES.getRes("dice_json"), RES.getRes("dice_png"));
        SceneManager.getInstance().showWindow(new helpScene());
    }
    onRemove() { }
    addToStage() { }

    private login() {
        let id = Number(this.idInput.text);
        let name = this.nameInput.text;
        globalObject.getInstance().debugConsole(`登录请求 id:${id} name:${name}`);
        if ((!id) || (!name)) {
            globalObject.getInstance().showTip("工号或姓名不合法！");
            return;
        }
        nano.request("gamemanager.login", {
            "account": id,
            "name": name
        }, (data) => {
            globalObject.getInstance().debugConsole("登录请求回调：", data);
            //登陆失败
            if (data.code == 500) {
                globalObject.getInstance().showTip(data.message);
                return;
            }
            //登陆成功
            else if (data.code == 200) {
                this.playerInfo.id = id;
                globalObject.getInstance().player.Username = name;
                SceneManager.getInstance().closeWindow();
                SceneManager.getInstance().changeScene(new introScene());
                globalObject.getInstance().showTip(data.message);
                //本地存储
                egret.localStorage.setItem("loginId", id.toString());
                egret.localStorage.setItem("loginName", name);
                return;
            }
        });
    }
}